import { Component, OnInit } from '@angular/core';
import { _HttpClient, SettingsService } from '@delon/theme';
import { NzNotificationService, NzMessageService, NzModalService } from 'ng-zorro-antd';
import { openWindow } from '@shared';
import { SocialService, ITokenModel } from '@delon/auth';

/**
 * 第三方账号绑定
 */
@Component({
  selector: 'app-third-bind',
  templateUrl: './third-bind.component.html',
  providers: [SocialService],
})
export class ThirdBindComponent implements OnInit {
  userLoading = false;
  user = null;
  constructor(
    public http: _HttpClient,
    private notice: NzNotificationService,
    private msg: NzMessageService,
    private setting: SettingsService,
    private socialService: SocialService,
    private confirm: NzModalService,
  ) {}

  ngOnInit() {
    this.init();
  }

  init() {
    this.userLoading = true;
    this.http.get(`/cf/admin/user/${this.setting.user.userId}`).subscribe(res => {
      this.userLoading = false;
      this.user = res.data;
    });
  }

  bind(third) {
    let url = '';
    let client_id = '';
    const redirect_uri = encodeURIComponent(window.location.origin + window.location.pathname + '/#/account/authredirect');
    if (third === 'dd') {
      client_id = 'dingoau3hvign0r6uosxbj';
      url = `https://oapi.dingtalk.com/connect/qrconnect?appid=${client_id}&response_type=code&scope=snsapi_login&state=DD-BIND&redirect_uri=${redirect_uri}`;
    }
    this.socialService
      .login(url, '/', {
        type: 'window',
      })
      .subscribe((res: ITokenModel) => {
        if (res) {
          this.init();
          this.notice.success('成功', '绑定成功');
        }
      });
  }

  unbind(third, name) {
    this.confirm.confirm({
      nzTitle: `确定解绑${name}账号?`,
      nzOnOk: () => {
        let type = '';
        if (third === 'dd') {
          type = 'DD';
        }
        this.http.post(`/cf/admin/social/unbind/${this.setting.user.userId}?type=${type}`).subscribe(res => {
          if (res.status === 200) {
            this.notice.success('成功', '解绑成功');
            this.init();
          }
        });
      },
    });
  }
}
